<template>
  <van-button
    v-if="value"
    round
    size="small"
    :loading="loading"
    @click="onFollow"
  >已关注</van-button>
  <van-button
    v-else
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    :loading="loading"
    @click="onFollow"
  >关注</van-button>
</template>

<script>
import { addFollow, deleteFollow } from '@/api/user'

export default {
  name: 'FollowUser',
  props: {
    // 是否关注了
  value: {
      type: Boolean,
      required: true
    },
    // 用户ID  
    userId: {
      type: [Number, String, Object],
      required: true
    }
  },
  data () {
    return {
      loading: false  // 加载中控制变量
    }
  },
  methods: {
    async onFollow () {
    
  	  if(!this.$store.state.user) return this.$toast('请登录！')  
        
      this.loading = true
      try {
        if (this.value) {
        
          await deleteFollow(this.userId)
        } else {
 
          await addFollow(this.userId)
        }


        this.$emit('input', !this.value)
      } catch (err) {
        console.log(err)
        if(err && err.response.status === 400){
            this.$toast('你不能关注自己')
        }else{
            this.$toast.fail('操作失败')
        }
      }
      this.loading = false // 关闭关注按钮的 loading 状态
    }
  }
}
</script>

<style scoped lang="less"></style>